package com.kotlin.demo.net;

import okhttp3.Interceptor
import okhttp3.Response
import okio.Buffer
import java.io.IOException
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException
import java.util.concurrent.TimeUnit
import org.slf4j.LoggerFactory

class HttpLogInterceptor : Interceptor {
    private val TAG = HttpLogInterceptor::class.java.simpleName
    private val UTF8 = Charset.forName("UTF-8")
    private val logger = LoggerFactory.getLogger(HttpLogInterceptor::class.java)

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val requestBody = request.body()
        var body: String? = null
        requestBody?.let {
            val buffer = Buffer()
            requestBody.writeTo(buffer)
            var charset: Charset? = UTF8
            val contentType = requestBody.contentType()
            contentType?.let {
                charset = contentType.charset(UTF8)
            }
            body = buffer.readString(charset!!)
        }

        logger.info("发送请求: method：{}", request.method())
        logger.info("url：{}", request.url())
        logger.info("请求头：{}", request.headers())
        logger.info("请求参数: {}", body)

        val startNs = System.nanoTime()
        val response = chain.proceed(request)
        val tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)

        val responseBody = response.body()
        val rBody: String

        val source = responseBody!!.source()
        source.request(java.lang.Long.MAX_VALUE)
        val buffer = source.buffer()

        var charset: Charset? = UTF8
        val contentType = responseBody.contentType()
        contentType?.let {
            try {
                charset = contentType.charset(UTF8)
            } catch (e: UnsupportedCharsetException) {
                println(e.message)
            }
        }
        rBody = buffer.clone().readString(charset!!)

        logger.info("收到响应: code:{}", response.code())
        logger.info("请求url：{}", response.request().url())
        logger.info("请求body：{}", body)
        logger.info("Response: {}", rBody)

        return response
    }
}
